﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using Mocola.BLL;
using Mocola.Model;
using System.Collections.Generic;
using Mocola.Security;

namespace Mocola.Net.Web.ajax
{
    /*Begin:[#20]*/
    public partial class DeleteNode : System.Web.UI.Page
    {
        /// <summary>
        /// 密码不匹配 -1
        /// 删除失败  -2
        /// 删除成功   0
        /// 文件记录数 n(n>0)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string pwd=Request.QueryString["pwd"];
            string uid = Request.QueryString["uid"];
            string eid=Request.QueryString ["eid"];

            #region
            if (ConfigurationManager.AppSettings["PasswordConfirm"].Equals("1"))
            {
                if (IsMatchPassword(pwd))
                {
                    int fileCount = ExistFiles(uid, eid);
                    if (fileCount > 0)//存在文件
                    {
                        Response.Write(fileCount.ToString());
                        return;
                    }
                    if (Delete(uid))
                    {
                        Response.Write("0");
                    }
                    else
                    {
                        Response.Write("-2");
                    }
                }
                else
                {
                    Response.Write("-1");
                }
            }
            else //无需密码验证
            {
                int fileCount = ExistFiles(uid, eid);
                if (fileCount > 0)//存在文件
                {
                    Response.Write(fileCount.ToString());
                    return;
                }
                if (Delete(uid))
                {
                    Response.Write("0");
                }
                else
                {
                    Response.Write("-2");
                }
            }
            #endregion
        }

        private string GetUID(string uid)
        {
            using (DataTable dt = Databases.MocolaNet.Select(Moc_TreesInfo.Moc_Trees, Moc_TreesInfo.Moc_Trees.UniqueID,
                Moc_TreesInfo.Moc_Trees.ParentID)
                .Where(Moc_TreesInfo.Moc_Trees.ParentID == uid).ToDataSet().Tables[0])
            {
                if (dt.Rows.Count > 0)
                {
                    return dt.Rows[0]["UniqueID"].ToString();
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 当前目录下文件记录数
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="eid"></param>
        /// <returns></returns>
        private int ExistFiles(string uid, string eid)
        {
            string sql = "select count([name]) from dbo.Moc_Maps where tid in({0}) and eid={1}";
            sql += " union all ";
            sql += "select count([name]) from dbo.Moc_files where tid in({0}) and eid={1}";
            string id = string.Join(",", GetIDCollection(uid).ToArray());
            sql = string.Format(sql, id, eid);
            IDataReader reader = Databases.MocolaNet.ExecuteReader(CommandType.Text, sql);
            int record = 0;
            while (reader.Read())
            {
                record += Convert.ToInt32(reader[0].ToString());
            }
            return record;
        }

        private bool IsMatchPassword(string pwd)
        {           
            string sql = "select UserPwd FROM Moc_Users where UserName='{0}'";
            sql = string.Format(sql, Page.User.Identity.Name);
            IDataReader reader = Databases.MocolaNet.ExecuteReader(CommandType.Text, sql);
            if (reader.Read())
            {
                MD5Verifier md5 = new MD5Verifier();
                return md5.verifyMd5Hash(pwd,reader["UserPwd"].ToString());
            }
            else
                return false;
        }


        /// <summary>
        /// 目录树UniquelID
        /// </summary>
        /// <returns></returns>
        private List<string> GetIDCollection(string uid)
        {
            List<string> list = new List<string>();
            while (uid != "")
            {
                list.Add(uid);
                uid = GetUID(uid);
            }
            return list;
        }

        private bool Delete(string uid)
        {
            try
            {
                string id = string.Join(",", GetIDCollection(uid).ToArray());
                string sql = string.Format("delete from dbo.Moc_Trees where uniqueid in({0})", uid);
                Databases.MocolaNet.ExecuteNonQuery(CommandType.Text, sql);
                return true;
            }
            catch (Exception er)
            {
                throw new Exception("删除导航节点时发生错误：" + er.Message);
            }
        }
    }
    /*End:[#20]*/
}
